<template>
  <div class="record-details">
    <el-button
        type="primary"
        icon="Download"
        :loading="isLoadingExport"
        @click="exportRecords"
        style="margin-bottom: 15px;"
    >
      导出签到记录
    </el-button>

    <el-table v-if="attendanceRecords.length > 0 && !isLoading" :data="attendanceRecords" style="width: 100%">
      <el-table-column prop="username" label="学生姓名"></el-table-column>
      <el-table-column prop="jobCode" label="学号"></el-table-column>
      <el-table-column prop="major" label="专业"></el-table-column>
      <el-table-column prop="className" label="班级"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot:default="scope">
          <span v-if="scope.row.status === '0'">已签到</span>
          <span v-else-if="scope.row.status === '1'">缺勤</span>
          <span v-else-if="scope.row.status === '2'">事假</span>
          <span v-else-if="scope.row.status === '3'">病假</span>
          <span v-else-if="scope.row.status === '4'">公假</span>
          <span v-else-if="scope.row.status === '5'">迟到</span>
          <span v-else-if="scope.row.status === '6'">早退</span>
          <span v-else-if="scope.row.status === '7'">待签到</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="签到时间"></el-table-column>
      <el-table-column label="操作" width="100">
        <template v-slot:default="scope">
          <el-button
              size="small"
              type="warning"
              @click="openStatusDialog(scope.row.id, scope.row.status)"
          >
            修改状态
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-else-if="!isLoading" style="text-align: center; padding: 20px;">
      暂无数据
    </div>

    <el-pagination
        v-if="totalRecords > 0 && !isLoading"
        :current-page="currentPage"
        :page-size="recordPageSize"
        :total="totalRecords"
        layout="prev, pager, next"
        @current-change="handleRecordPageChange"
    ></el-pagination>

    <!-- 状态修改对话框 -->
    <el-dialog
        v-model="statusDialogVisible"
        title="修改签到状态"
        width="40%"
    >
      <div v-if="statusRecordId">
        <p>学生：{{ statusRecordUsername }}</p>
        <p>当前状态：{{ getStatusText(statusRecordCurrentStatus) }}</p>
        <el-radio-group v-model="selectedStatus">
          <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="cancelStatusChange">取 消</el-button>
          <el-button type="primary" @click="confirmStatusChange">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import throttle from 'lodash/throttle';
import store from "@/store";

const api = axios.create({
  baseURL: store.getters.getBaseURL
});

// 添加请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister';
      }
      return Promise.reject(error);
    }
);

export default {
  props: {
    aid: {
      type: Number,
      required: true
    },
    recordPageSize: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      attendanceRecords: [],
      totalRecords: 0,
      currentPage: 1,
      isLoading: false,
      isLoadingExport: false,
      resizeObserver: null,
      statusDialogVisible: false,
      statusRecordId: null,
      statusRecordUsername: '',
      statusRecordCurrentStatus: null,
      selectedStatus: null,
      pollInterval: null // 新增：轮询定时器
    };
  },
  computed: {
    statusOptions() {
      return [
        { label: '已签到', value: '0' },
        { label: '缺勤', value: '1' },
        { label: '事假', value: '2' },
        { label: '病假', value: '3' },
        { label: '公假', value: '4' },
        { label: '迟到', value: '5' },
        { label: '早退', value: '6' },
        { label: '待签到', value: '7' }
      ];
    }
  },
  watch: {
    aid: {
      immediate: true,
      handler(newAid) {
        if (newAid) {
          this.throttledGetAttendanceRecords(newAid);
          this.startPolling(); // 启动轮询
        }
      }
    }
  },
  methods: {
    // 节流处理获取签到记录详情
    throttledGetAttendanceRecords: throttle(function(aid) {
      this.getAttendanceRecords(aid);
    }, 200),
    // 获取签到记录详情
    getAttendanceRecords(aid) {
      if (this.isLoading) return; // 防止重复请求
      this.isLoading = true;

      api.get(`/record/${aid}?pageNo=${this.currentPage}&pageSize=${this.recordPageSize}`)
          .then(response => {
            if (response.data.status === 'success') {
              this.attendanceRecords = response.data.data.list;
              this.totalRecords = response.data.data.resultCount;
            } else {
              ElMessage.error(response.data.info || '获取签到记录失败');
            }
          })
          .catch(error => {
            console.error('Error fetching attendance records:', error);
            ElMessage.error('获取签到记录失败');
          })
          .finally(() => {
            this.isLoading = false;
          });
    },
    // 处理签到记录分页变化
    handleRecordPageChange(page) {
      this.currentPage = page;
      if (this.aid) {
        this.throttledGetAttendanceRecords(this.aid);
      }
    },
    // 导出签到记录
    exportRecords() {
      if (!this.aid) {
        ElMessage.error('活动ID为空，无法导出');
        return;
      }

      this.isLoadingExport = true;

      api.get(`/excel/export?aid=${this.aid}`, {
        responseType: 'blob' // 重要：设置响应类型为blob
      })
          .then(response => {
            // 创建下载链接
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '签到记录.xlsx');
            document.body.appendChild(link);
            link.click();

            // 清理
            link.remove();
            window.URL.revokeObjectURL(url);

            ElMessage.success('导出成功');
          })
          .catch(error => {
            console.error('Export error:', error);
            ElMessage.error('导出失败');
          })
          .finally(() => {
            this.isLoadingExport = false;
          });
    },
    // 打开状态修改对话框
    openStatusDialog(recordId, currentStatus) {
      const record = this.attendanceRecords.find(
          record => record.id === recordId
      );

      if (record) {
        this.statusDialogVisible = true;
        this.statusRecordId = record.id;
        this.statusRecordUsername = record.username;
        this.statusRecordCurrentStatus = currentStatus;
        this.selectedStatus = currentStatus;
      }
    },
    // 取消状态修改
    cancelStatusChange() {
      this.statusDialogVisible = false;
      this.statusRecordId = null;
      this.statusRecordUsername = '';
      this.statusRecordCurrentStatus = null;
      this.selectedStatus = null;
    },
    // 确认状态修改
    confirmStatusChange() {
      if (!this.statusRecordId) return;

      if (this.selectedStatus === this.statusRecordCurrentStatus) {
        ElMessage.info('新状态与当前状态相同，无需修改');
        this.cancelStatusChange();
        return;
      }

      api.put(`/record/modifyRecordStatus/${this.statusRecordId}`, {
        status: this.selectedStatus
      })
          .then(response => {
            if (response.data.status === 'success') {
              // 更新本地数据
              const recordIndex = this.attendanceRecords.findIndex(record => record.id === this.statusRecordId);
              if (recordIndex !== -1) {
                this.attendanceRecords[recordIndex].status = this.selectedStatus;
                ElMessage.success('状态修改成功');
              }
            } else {
              ElMessage.error(response.data.info || '状态修改失败');
            }
          })
          .catch(error => {
            console.error('Error modifying status:', error);
            ElMessage.error('状态修改失败');
          })
          .finally(() => {
            this.cancelStatusChange();
          });
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '已签到',
        '1': '缺勤',
        '2': '事假',
        '3': '病假',
        '4': '公假',
        '5': '迟到',
        '6': '早退',
        '7': '待签到'
      };
      return statusMap[status] || status;
    },
    // 启动轮询
    startPolling() {
      this.stopPolling(); // 清除之前的轮询
      if (this.aid) {
        this.pollInterval = setInterval(() => {
          this.throttledGetAttendanceRecords(this.aid);
        }, 5000); // 每3秒轮询一次
      }
    },
    // 停止轮询
    stopPolling() {
      if (this.pollInterval) {
        clearInterval(this.pollInterval);
        this.pollInterval = null;
      }
    }
  },
  mounted() {
    // 避免重复创建 ResizeObserver
    if (!this.resizeObserver) {
      this.resizeObserver = new ResizeObserver(throttle(() => {
      }, 200));
      this.resizeObserver.observe(this.$el);
    }
  },
  beforeUnmount() {
    // 销毁 ResizeObserver 和轮询定时器
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    this.stopPolling();
  }
};
</script>

<style scoped>
.record-details {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 15px;
  color: #333;
}

.el-pagination {
  margin-top: 15px;
  text-align: center;
}
</style>